package org.springblade.modules.app.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springblade.common.config.AlibabaOSSConfig;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("blade-app/filemgr")
public class FilemgrController extends BladeController {

    @PostMapping("/fileupload")
    public R save(@RequestParam(value = "file") MultipartFile multipartFile) {
        ///  abcdefg.pdf
        String fileFullName = multipartFile.getOriginalFilename();
        /// .pdf
        String fileSuffix = fileFullName.substring(fileFullName.lastIndexOf("."), fileFullName.length());
        /// xxx.pdf
        String fileMd5FullName = IdWorker.getIdStr() + fileSuffix;
        /// 上传
        OSS ossClient = new OSSClientBuilder().build(AlibabaOSSConfig.endpoint, AlibabaOSSConfig.accessKeyId, AlibabaOSSConfig.accessKeySecret);
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            return R.fail("上传失败");
        }
        ossClient.putObject(AlibabaOSSConfig.bucketName, fileMd5FullName, inputStream);
        ossClient.shutdown();
        String resourcePath = AlibabaOSSConfig.url + "/" + fileMd5FullName;
            Map<String, String> map = new HashMap<>();
            map.put("name", fileMd5FullName);
            map.put("url", resourcePath);
        return R.data(map);
    }

}
